"use strict";
////////////全局变量//////////////\
var  exercises=[];//欲创建的习题
var  oldExercises=[];//已创建习题
function setParentHeight(){
		// 子页面设置父页面iframe高度
    if(window.parent.sethomeworkIframeheight){
        var ht=$("#container").height();
		ht=ht>535?ht:535;
        window.parent.sethomeworkIframeheight(ht);
    }
}
$(function(){
    $("#addQuestion_wenda").click(creat_wenda);
    $("#addQuestion_xuanzhe").click(creat_choice);
    $("#addQuestion_tiankong").click(creat_fillBlank);
    getLabExercises();
    //模态框每次关闭恢复初始
    var OldHtml;
    $("div.modal.fade").on("show.bs.modal",function(){
        OldHtml=$(this).html();
    });
    $("div.modal.fade").on("hidden.bs.modal",function(){
        $(this).html(OldHtml);
    });
});
function  getLabExercises(){
    $.ajax({
        url:"querstion_query.action",
        type:"POST",
        data:{"lad_id_new":LessonID},
        dataType:"json",
        success:function(data){
            if(data.succeed=="true") {
                //success

                oldExercises=data.data;
                fillOldExs();
            }
            else {
                window.parent.childmsg(langThis("lab_queryEFail"));
            }
            setParentHeight();
        },
        error:function(event){
            window.parent.childmsg(langThis("lab_queryEFail"));
            setParentHeight();
        }
    });
}
function  fillOldExs(){
    for (var i in oldExercises){
        var theOldE=oldExercises[i];

        addOLdExercisesULItem(theOldE);
    }
}
function  creat_wenda(){
    $('#modal_creatWenda').modal({show:true,backdrop:'static'});
}
function  creat_choice(){
    $('#modal_creatChoice').modal({show:true,backdrop:'static'});
}
function  creat_fillBlank(){
    $('#modal_creatFillBlank').modal({show:true,backdrop:'static'});
}
function  insertBalnk(){
    var temp=$("#fillBlankTitle");
    var  theStr=temp.val()+"____";//4个下划线
    temp.val(theStr);
    temp.focus();
}
function  pushOneFillblank(){
    var txt=  $("#fillBlankTitle");
    var title=txt.val();
    var  score=$("#fillblankScore").val();
    title=title.replace(/____/g,"&kong&");//替换空格标示符
    if(title==""||title==undefined||score==""){
        window.parent.childmsg(langThis("nav_notEmpty"));
        return;
    }
    if(isNaN(score)){
        window.parent.childmsg(langThis("lab_scoreNaN"));
        return;
    }
    var fillblank={
        type:3,
        title:title,
        score:score
    };
    exercises.push(fillblank);
    addExercisesULItem(fillblank);
    var ischecked=  $("#modal_creatFillBlank .notCloseWindow_cbx").is(':checked');
    if(ischecked){
        txt.val("");
        window.parent.childmsg(langThis("lab_creatSuc"));
    }
    else {
        txt.val("");
        $('#modal_creatFillBlank').modal("hide");
        window.parent.childmsg(langThis("lab_creatSuc"));
    }
}
function  pushOneWenda(){
    var txt=  $("#wendaTitle");
    var title=txt.val();
    var  score=$("#wendaScore").val();
    if(title==""||title==undefined||score==""){
        window.parent.childmsg(langThis("nav_notEmpty"));
        return;
    }
    if(isNaN(score)){
        window.parent.childmsg(langThis("lab_scoreNaN"));
        return;
    }
    var wenda={
        type:2,
        title:title,score:score
    };
    exercises.push(wenda);
    addExercisesULItem(wenda);
    var ischecked=  $("#modal_creatWenda .notCloseWindow_cbx").is(':checked');
    if(ischecked){
        txt.val("");
       window.parent.childmsg(langThis("lab_creatSuc"));
    }
    else {
        txt.val("");
        $('#modal_creatWenda').modal("hide");
        window.parent.childmsg(langThis("lab_creatSuc"));
    }
}
function  pushOneChoice(){
    var  txt=  $("#choiceTitle");
    var title=txt.val();
    var  score=$("#choiceScore").val();
    if(isNaN(score)){
        window.parent.childmsg(langThis("lab_scoreNaN"));
        return;
    }
    var valied=true;
    if(title==""||title==undefined){
        valied=false;
    }
    var choice={
        type:1,
        title:title,
        score:score,
        T:"",
        info:{}
    }
    $("#choiceList").children().each(function(index,e){
        var  itemVal= $(this).val();
        if(itemVal==""||itemVal==undefined){
            valied=false;
        }
        var cLabelCode="A".charCodeAt(0)+ index;
        var cLabel=String.fromCharCode(cLabelCode);
        choice.info[cLabel]=itemVal;
    });

    $("#choiceAnswerList").find("input:checkbox").each(function (index,e){
        if(this.checked){
            choice.T+=$(this).parent().text();
        }
    });
    if(valied){
        exercises.push(choice);
        addExercisesULItem(choice);
        var ischecked=  $("#modal_creatChoice .notCloseWindow_cbx").is(':checked');
        if(ischecked){
            txt.val("");
            $("#choiceList").children().val("");
            window.parent.childmsg(langThis("lab_creatSuc"));
        }
        else {
            txt.val("");
            $("#choiceList").children().val("");
            $('#modal_creatChoice').modal("hide");
            window.parent.childmsg(langThis("lab_creatSuc"));
        }
    }
    else {
        window.parent.childmsg(langThis("nav_notEmpty"));
        return;
    }
}
function  addChoiceItem(){
    var str="<input type=\"text\" class=\"form-control modalcontrol_lab\">";
    var choiceList=$("#choiceList");
    choiceList.append(str);

    var cLabelCode="A".charCodeAt(0)+ choiceList.children().length-1;
    var cLabel=String.fromCharCode(cLabelCode);
    var str1="<label><input type=\"checkbox\">"+cLabel+"</label>";
    $("#choiceAnswerList").append(str1);
}
function removeChoiceItem(){
    $("#choiceList").children().last().remove();
    $("#choiceAnswerList").children().last().remove();
}
function  addOLdExercisesULItem(item){
    var imgsrc="";
    var fun="";
    if(item.t_querstion_type_id==1){
        imgsrc="imgs/icon_choice.png";
        fun="modifychoice(this)";
    }
    else  if(item.t_querstion_type_id==2){
        imgsrc="imgs/icon_question.png";
        fun="modifyanswer(this)";
    }
    else {
        imgsrc="imgs/icon_fillblank.png";
        fun="modifyfilling(this)";
    }
    var thetile=item.t_querstion_title;
    if(item.t_querstion_type_id==3){
        thetile=thetile.replace(/&kong&/g,"____");
    }
    var str="<li class=\"list-group-item exercisesitem\" ><div onclick="+fun+" id='eArrID_"+item.t_querstion_id+"'><img src="+imgsrc+">"+thetile+"</div><img id='eArrID_"+item.t_querstion_id+"' class='querstion_dltimg' src='./imgs/delete.png' onclick=\"deleteThisOldExercisesItem(this)\"></li>";
    $(".exercises").append(str);
    setParentHeight();
}
function  addExercisesULItem(item){
    var imgsrc="";
    var fun="";
    if(item.type==1){
        imgsrc="imgs/icon_choice.png";
        fun="modifychoice(this)";
    }
    else  if(item.type==2){
        imgsrc="imgs/icon_question.png";
        fun="modifyanswer(this)";
    }
    else {
        imgsrc="imgs/icon_fillblank.png";
        fun="modifyfilling(this)";
    }
    var thetile=item.title;
    if(item.type==3){
        thetile=thetile.replace(/&kong&/g,"____");
    }
    var str="<li class=\"list-group-item exercisesitem\"><div onclick="+fun+"><img src="+imgsrc+">"+thetile+"</div><img data-type='"+item.type+"' data-title='"+thetile+"' class='querstion_dltimg' src='./imgs/delete.png' onclick=\"deleteThisOldExercisesItem(this)\"></li>";
    $(".exercises").append(str);
    setParentHeight();
}
//修改显示习题
function modifyExercisesULItem(dom,title,flag){
    // var id
    var Mdfdom=$(dom);
    var newhtml=Mdfdom.html().split(">")[0]+">"+title.replace(/&kong&/g,"____");
    Mdfdom.html(newhtml);
    if(flag){
        Mdfdom.next("img").attr("data-title",title);
    }
}
function  deleteThisOldExercisesItem(e){

     layer.confirm(langThis("lab_delConfirm"),{btn:[
        langThis("pm_confirm"),
        langThis("pm_cancle")
    ], title:langThis("lab_atten")},function(){
         layer.closeAll();
        var questionId= e.id.split("_")[1];
        if(typeof(questionId)=="undefined" || questionId=="undefined"){
            for(var i in exercises){
                if(exercises[i].type==e.getAttribute("data-type") && exercises[i].title==e.getAttribute("data-title")){
                    exercises.splice(i,1);
                    break;
                }
            }
            $(e).parent("li").remove();
            return;
        }
        $.ajax({
            url:"querstion_delete.action",
            type:"POST",
            data:{"querstion_id":questionId},
            dataType:"json",
            success:function(data){
                if(data.succeed=="true") {
                    //success
                    $(e).parent("li").remove();
                }
                else {
                    window.parent.childmsg(langThis("lab_delExFail"));
                }
            },
            error:function(event){
                window.parent.childmsg(langThis("lab_delExFail"));
            }
        });
    },function(){ layer.closeAll();});
}
function  deleteThisExercisesItem(e){

     layer.confirm(langThis("lab_delConfirm"),{btn:[
        langThis("pm_confirm"),
        langThis("pm_cancle")
    ], title:langThis("lab_atten")},function(){
        layer.closeAll();
        var theTitleTxt= $(e).text();
        for(var i in  exercises){
            if(exercises[i].title==theTitleTxt){
                exercises.splice(i,1);
            }
        }
        $(e).remove();
    },function(){layer.closeAll();});
}
function uploadExercises(){
    if(exercises.length<1){
        window.parent.childmsg(langThis("lab_modifyFinish"));
        return;
    }

    var obj={"exercises":exercises}

    var objStr = JSON.stringify(obj);
    //window.parent.childmsg(objStr);
    //使用jQuery中的$.ajax({});Ajax方法
    $.ajax({
        url:"querstion_insert.action",
        type:"POST",
        data:{"exercises":objStr,
            "lad_id_new":LessonID
        },
        dataType:"json",
        success:function(data){
            if(data.succeed=="true"){
                window.parent.childmsg(langThis("lab_modifyFinish"));
                exercises=[];
            }
            else {
                window.parent.childmsg(langThis("lab_labfail"));
            }
        },
        error:function(event){
            window.parent.childmsg(langThis("lab_labfail"));
        }
    });
}
// 修改习题
    //问答
function modifyanswer(e){
    //修改原有的/新赠的
    var id=e.id.split("_")[1];
    var selected=getCurrentMdy(2,id,$(e).text());
    //填充模态框
    var model=$("#modal_creatWenda");
    model.modal('show');
    model.find("h4.modal-title").text(langThis("lab_mdfquestion"));//标题
    model.find("div.modal-footer>label").hide();//继续添加
    model.find("div.modal-footer>button:last-child").text(langThis("pm_modify"));//按钮
    $("#wendaTitle").val(selected.data.title);//问题
    $("#wendaScore").val(selected.data.score);//分数
    model.find("div.modal-footer>button:last-child").attr("onclick",null);
    model.find("div.modal-footer>button:last-child").click(function(){
        var title=$("#wendaTitle").val().trim();
        var  score=$("#wendaScore").val().trim();
        if(title==""||title==undefined||score==""){
            window.parent.childmsg(langThis("nav_notEmpty"));
            return;
        }
        if(isNaN(score)){
            window.parent.childmsg(langThis("lab_scoreNaN"));
            return;
        }
        if(selected.flag){//修改原有的
            oldExercises[selected.pos].t_querstion_title=title;
            oldExercises[selected.pos].t_question_score=score;
            updatequerstion(selected.data.id,title,null,null,score,function(info){
                modifyExercisesULItem(e,title,false);
                model.modal("hide");
            });
        }else{
            exercises[selected.pos].title=title;
            exercises[selected.pos].score=score;
            modifyExercisesULItem(e,title,true);
            model.modal("hide");
        }
    });
}
    //选择
function modifychoice(e){
    //修改原有的/新赠的
    var id=e.id.split("_")[1];
    var selected=getCurrentMdy(1,id,$(e).text());
    //填充模态框
    var model=$("#modal_creatChoice");
    model.modal('show');
    model.find("h4.modal-title").text(langThis("lab_mdfchoice"));//标题
    model.find("div.modal-footer>label").hide();//继续添加
    model.find("div.modal-footer>button:last-child").text(langThis("pm_modify"));//按钮
    $("#choiceTitle").val(selected.data.title);//问题
    $("#choiceScore").val(selected.data.score);//分数
    //选项个数
    var num=Object.getOwnPropertyNames(selected.data.info).length;
    if(num<2){
        while (2-num) {
            removeChoiceItem();
            num++;
        }
    }else{
        while (num-2) {
            addChoiceItem();
            num--;
        }
    }
    //勾选正确项
    $("#choiceAnswerList>label").each(function(index,e){
        for(var i in selected.data.T){
            if($(e).text()==selected.data.T[i]){
                $(e).children().prop("checked",true);
                break;
            }
        }
    });
    //填充习题
    var childnum=1;
    for(var j in selected.data.info){
        var selector="#choiceList>input[type='text']:nth-child("+childnum+")";
        $(selector).val(selected.data.info[j]);
        childnum++;
    }

    model.find("div.modal-footer>button:last-child").attr("onclick",null);
    model.find("div.modal-footer>button:last-child").click(function(){
        var title=$("#choiceTitle").val().trim();
        var  score=$("#choiceScore").val().trim();
        if(isNaN(score)){
            window.parent.childmsg(langThis("lab_scoreNaN"));
            return;
        }
        var valied=true;
        if(title==""||title==undefined){
            valied=false;
        }
        var info={};
        $("#choiceList>input").each(function(index,e){
            var  itemVal= $(e).val().trim();
            if(itemVal==""||itemVal==undefined){
                valied=false;
                return;
            }
            var cLabelCode="A".charCodeAt(0)+ index;
            var cLabel=String.fromCharCode(cLabelCode);
            info[cLabel]=itemVal;
        });
        if(!valied){
            window.parent.childmsg(langThis("nav_notEmpty"));
            return;
        }
        var T="";
        $("#choiceAnswerList>label>input[type='checkbox']").each(function (index,e){
            if(e.checked){
                T+=$(e).parent().text();
            }
        });

        if(selected.flag){//修改原有的
            oldExercises[selected.pos].t_querstion_title=title;
            oldExercises[selected.pos].t_question_score=score;
            oldExercises[selected.pos].t_question_keys=T;
            var oldchoicenum=0;
            for(var i in info){
                if(!oldExercises[selected.pos].list_t_q_choiceitem[oldchoicenum]){
                    oldExercises[selected.pos].list_t_q_choiceitem[oldchoicenum]={};
                }
                oldExercises[selected.pos].list_t_q_choiceitem[oldchoicenum].choiceitem_title=info[i];
                oldchoicenum++;
            }
            while(oldExercises[selected.pos].list_t_q_choiceitem.length-oldchoicenum>0){
                oldExercises[selected.pos].list_t_q_choiceitem.pop();
            }
            var content="";
            updatequerstion(selected.data.id,title,content,T,score,function(info){
                modifyExercisesULItem(e,title,false);
                model.modal("hide");
            });
        }else{
            exercises[selected.pos].title=title;
            exercises[selected.pos].score=score;
            exercises[selected.pos].info=info;
            exercises[selected.pos].T=T;
            modifyExercisesULItem(e,title,true);
            model.modal("hide");
        }
    });
}
    //填空
function modifyfilling(e){
    //修改原有的/新赠的
    var id=e.id.split("_")[1];
    var selected=getCurrentMdy(3,id,$(e).text().replace(/____/g,"&kong&"));
        //填充模态框
    var model=$("#modal_creatFillBlank");
    model.modal('show');
    model.find("h4.modal-title").text(langThis("lab_mdffillBlank"));//标题
    model.find("div.modal-footer>label").hide();//继续添加
    model.find("div.modal-footer>button:last-child").text(langThis("pm_modify"));//按钮
    $("#fillBlankTitle").val(selected.data.title.replace(/&kong&/g,"____"));//问题
    $("#fillblankScore").val(selected.data.score);//分数
    model.find("div.modal-footer>button:last-child").attr("onclick",null);
    model.find("div.modal-footer>button:last-child").click(function(){
        var title= $("#fillBlankTitle").val().trim();
        var  score=$("#fillblankScore").val().trim();
        title=title.replace(/____/g,"&kong&");//替换空格标示符
        if(title==""||title==undefined||score==""){
            window.parent.childmsg(langThis("nav_notEmpty"));
            return;
        }
        if(isNaN(score)){
            window.parent.childmsg(langThis("lab_scoreNaN"));
            return;
        }

        if(selected.flag){//修改原有的
            oldExercises[selected.pos].t_querstion_title=title;
            oldExercises[selected.pos].t_question_score=score;
            updatequerstion(selected.data.id,title,null,null,score,function(info){
                modifyExercisesULItem(e,title,false);
                model.modal("hide");
            });
        }else{
            exercises[selected.pos].title=title;
            exercises[selected.pos].score=score;
            modifyExercisesULItem(e,title,true);
            model.modal("hide");
        }
    });
}
//对比、获取当前选中项，并标记是新增的还是原有的
function getCurrentMdy(type,id,title)
{
    var res={};
    var temp,pos,flag;
    var arrtoobj=function(arr){
        var obj={},choice=65;
        for(var i in arr){
            obj[String.fromCharCode(choice)]=arr[i].choiceitem_title;
            choice++;
        }
        return obj;
    };
    if(!id){
        for(var i in exercises){
            if(exercises[i].title==title && exercises[i].type==type){
                temp=exercises[i];
                pos=i;
                flag=false;
                break;
            }
        }
    }else{
        id=parseInt(id);
        for(var j in oldExercises){
            if(oldExercises[j].t_querstion_id==id){
                pos=j;
                flag=true;
                switch(type){
                    case 1:temp={
                        T:oldExercises[j].t_question_keys,
                        info:arrtoobj(oldExercises[j].list_t_q_choiceitem),
                        score:oldExercises[j].t_question_score,
                        title:oldExercises[j].t_querstion_title,
                        type:1,
                        id:oldExercises[j].t_querstion_id
                    };break;
                    case 2:temp={
                        score:oldExercises[j].t_question_score,
                        title:oldExercises[j].t_querstion_title,
                        type:2,
                        id:oldExercises[j].t_querstion_id
                    };break;
                    case 3:temp={
                        score:oldExercises[j].t_question_score,
                        title:oldExercises[j].t_querstion_title,
                        type:3,
                        id:oldExercises[j].t_querstion_id
                    };break;
                    default:temp=false;
                }
                break;
            }
        }
    }
    res.data=temp;
    res.flag=flag;
    res.pos=pos;
    return res;
}
//修改习题服务
function updatequerstion(id,title,content,keys,score,sucessfun){
    $.ajax({
        url:"querstion_update.action",
        type:"POST",
        data:{
            "question.t_querstion_id":id,
            "question.t_querstion_title":title,
            "question.t_qurstion_content":content,
            "question.t_question_keys":keys,
            "question.t_question_score":score
        },
        dataType:"json",
        success:sucessfun,
        error:function(event){
            window.parent.childmsg(langThis("lab_erroronmdf"));
        }
    });
}